package com.backend.demo1.controller;

import com.backend.demo1.config.ApiResponse;
import com.backend.demo1.models.User;
import com.backend.demo1.services.AuthService;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;

import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    private static final long CAPTCHA_EXPIRATION_TIME = 5 * 60 * 1000; // 5分钟

    public enum CaptchaValidationResult {
        VALID,          // 验证码有效
        EXPIRED,        // 验证码过期
        INVALID         // 验证码错误
    }

    

    private CaptchaValidationResult validateCaptcha(HttpSession session, String userCaptcha) {
        String sessionCaptcha = (String) session.getAttribute("captcha");
        Long captchaTime = (Long) session.getAttribute("captchaTime");
    
        // 检查验证码是否过期
        if (captchaTime == null || System.currentTimeMillis() - captchaTime > CAPTCHA_EXPIRATION_TIME) {
            return CaptchaValidationResult.EXPIRED;
        }
    
        // 检查验证码是否错误
        if (sessionCaptcha == null || !sessionCaptcha.equals(userCaptcha)) {
            return CaptchaValidationResult.INVALID;
        }
    
        // 验证码有效
        return CaptchaValidationResult.VALID;
    }
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<String>> register(@RequestBody User user, HttpSession session) {
        CaptchaValidationResult validationResult = validateCaptcha(session, String.valueOf(user.getCaptcha()));

        // 根据验证结果返回不同的响应
        if (validationResult == CaptchaValidationResult.EXPIRED) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "验证码已过期", null));
        } else if (validationResult == CaptchaValidationResult.INVALID) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "验证码错误", null));
        }

        // 调用注册逻辑
        String token = authService.register(user);
        return ResponseEntity.ok(new ApiResponse<>(200, "注册成功", token));
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@RequestBody User input, HttpSession session) {
        CaptchaValidationResult validationResult = validateCaptcha(session, String.valueOf(input.getCaptcha()));

        // 根据验证结果返回不同的响应
        if (validationResult == CaptchaValidationResult.EXPIRED) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "验证码已过期", null));
        } else if (validationResult == CaptchaValidationResult.INVALID) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "验证码错误", null));
        }

        // 调用登录逻辑
        Map<String, Object> response = authService.login(input);
        return ResponseEntity.ok(new ApiResponse<>(200, "登录成功", response));
    }

    @GetMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpSession session) throws IOException {
        // 自定义纯字母的验证码（随机4位字母，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("abcdefghijklmnopqrstuvwyzx", 4);
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100);
        captcha.setGenerator(randomGenerator);
        captcha.createCode();
    
        // 将验证码和生成时间存储到 Session 中
        session.setAttribute("captcha", captcha.getCode());
        session.setAttribute("captchaTime", System.currentTimeMillis());
    
        // 设置响应头
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // System.out.println("Generated Captcha: " + captcha.getCode());
    
        // 输出验证码图片
        try (var out = response.getOutputStream()) {
            captcha.write(out);
        } catch (IOException e) {
            // 记录日志或处理异常
            e.printStackTrace();
        }
        response.getOutputStream().close();
    }
}